package io.mft.dev.base.cat;

import java.io.File;
import java.io.Serializable;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

import com.dianping.cat.Cat;

import io.mft.commons.config.ConfigProvider;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CatContext implements Cat.Context, Serializable {

	private static final InheritableThreadLocal<CatContext> THREADLOCAL = new InheritableThreadLocal<CatContext>();
	public static void initCatConfig() {
		try {
			URL url = CatContext.class.getClassLoader().getResource(".");
			String path=url.getPath()+File.separator+"cat"+File.separator;
			System.setProperty("CAT_HOME", path);
			int mode= ConfigProvider.get("system.cat.devMode", 0);
			if (mode==1) {
				System.setProperty("devMode", "true");
			}
			if (Thread.currentThread().getContextClassLoader() == null) {
				Thread.currentThread().setContextClassLoader(CatContext.class.getClassLoader());
			}
			Cat.initialize();
			Cat.enable();
			log.warn("CAT监控初始化完毕");
		} catch (Throwable e) {
			log.error("", e);
		}
	}
	private static final long serialVersionUID = -1L;

	private Map<String, String> property = new HashMap<String, String>();

	@Override
	public void addProperty(String key, String value) {
		property.put(key, value);
	}
	public static CatContext get() {
		return THREADLOCAL.get();
	}
	@Override
	public String getProperty(String key) {
		return property.get(key);
	}
	
	public static CatContext  instanceThreadCatContext() {
		CatContext catContext=get();
		if (catContext==null) {
			catContext=new CatContext();
			Cat.logRemoteCallClient(catContext);
		}
		return catContext;
	}
	public static void set(CatContext catContext) {
		THREADLOCAL.set(catContext);
	}
	
	public static void remove() {
		THREADLOCAL.remove();
	}
}
